package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import com.example.xcService.pojo.tool.StringTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.*;
/**
 * 奈雪官方接口
 * **/
@Slf4j
public class Plugin_ECARD_P009 implements ChannelService {
    public ChannelResult QueryBalance(JSONObject apiConfig){
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    public  ChannelResult Submit(JSONObject apiConfig, Map<String,Object> data){

        try {

            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));

            Map dataParams = new LinkedHashMap<String, String>();
            dataParams.put("phoneNumber",dataConfig.getString("AccountVal"));
            dataParams.put("activeCode",dataConfig.getString("SUPProductId"));
            dataParams.put("serialNo",dataConfig.getString("ChannelOrderCode"));

            //获取随机字符串
            String Nonce = StringTool.GetRandomText(5);
            //获取10位数时间戳
            String curTime=String.valueOf(System.currentTimeMillis()/1000);

            Map signParams = new LinkedHashMap<String, String>();
            signParams.put("Nonce",Nonce);
            signParams.put("Partner-Id",apiConfig.getString("USERID"));
            signParams.put("Secret-Key",apiConfig.getString("SecretKey"));
            signParams.put("Timestamp",curTime);

            //获取签名字符串
            String str = getSignStr(signParams);
           //获取sha1签名
            String Signature = shaEncode(str);

            signParams.put("Signature",Signature);
            signParams.remove("Secret-Key");


            String url=apiConfig.getString("SubmitURL");

            String responseContent = sendPost(url,signParams,dataParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("code");
            String msg = retobj.getString("message");
            Boolean status = retobj.getBoolean("success");
            if (code.equals("0") && status) {
                return ChannelResult.IN_PROCESS();
            }else {
                return ChannelResult.FAILED(status+","+msg);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            log.error("奈雪提交订单接口错误：",ex);
            return  ChannelResult.error("奈雪提交订单接口错误");
        }
    }

    public  ChannelResult Query(JSONObject apiConfig,Map<String,Object> data) {
        try {



            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));

            Map dataParams = new LinkedHashMap<String, String>();
            dataParams.put("serialNo",dataConfig.getString("ChannelOrderCode"));

            //获取随机字符串
            String Nonce = StringTool.GetRandomText(5);
            //获取10位数时间戳
            String curTime=String.valueOf(System.currentTimeMillis()/1000);

            Map signParams = new LinkedHashMap<String, String>();
            signParams.put("Nonce",Nonce);
            signParams.put("Partner-Id",apiConfig.getString("USERID"));
            signParams.put("Secret-Key",apiConfig.getString("SecretKey"));
            signParams.put("Timestamp",curTime);

            //获取签名字符串
            String str = getSignStr(signParams);
            //获取sha1签名
            String Signature = shaEncode(str);

            signParams.put("Signature",Signature);
            signParams.remove("Secret-Key");

            String url = apiConfig.getString("QueryURL");
            String responseContent = sendPost(url,signParams, dataParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("code");
            String msg = retobj.getString("message");
            Boolean status = retobj.getBoolean("success");
            if (code.equals("0") && status) {
                String OrderStatus = retobj.getString("OrderStatus");
                JSONObject orderData=retobj.getJSONObject("data");
                Boolean isSuccess=orderData.getBoolean("isSuccess");
                if (isSuccess) {
//
//                    return ChannelResult.success(orderData.getJSONArray("couponCodeList").get(0),"充值成功");
                    return ChannelResult.success("充值成功");
                }else  if (!isSuccess){
                    return ChannelResult.FAILED();
                }
                return  ChannelResult.error(OrderStatus);
            }else {
                return ChannelResult.error(status+","+msg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("奈雪查询订单接口错误：", ex);
            return ChannelResult.error("奈雪查询订单接口错误");
        }
    }

    public  ChannelResult Notify(JSONObject apiConfig, Map<String,Object> data){
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");

    }


    public static String sendPost(String url,Map<String,String> head,Map<String,String> param) {
        String result = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
            httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(param),"utf-8"));
            httpPost.setHeader("Nonce",head.get("Nonce"));
            httpPost.setHeader("Partner-Id",head.get("Partner-Id"));
            httpPost.setHeader("Signature",head.get("Signature"));
            httpPost.setHeader("Timestamp",head.get("Timestamp"));
            log.info("httpPost请求："+url+"?"+JSONObject.toJSONString(param));
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                result= EntityUtils.toString(responseEntity);
                log.info("httpPost请求返回："+JSONObject.toJSONString(result));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }


    public static String shaEncode(String inStr) throws Exception {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = inStr.getBytes("UTF-8");
        byte[] md5Bytes = sha.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }


    /**
     * 生成签名
     *
     * @param map
     * @return
     */
    public static String getSignStr(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
//            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
//
//                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
//                    return (o1.getKey()).toString().compareTo(o2.getKey());
//                }
//            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + val);
                    }
                }
            }
            result = sb.toString();
        } catch (Exception e) {
            log.error("获取签名明文出错：", e);
            return null;
        }
        return result;
    }
}
